-module(jobs).
-compile(export_all).

edges_and_vertices() ->
	PCS = [pcs_sm3,pcs_sm4],
	EXE = [exe_win32_release,exe_win64_release,exe_win32_shipping,exe_win64_shipping,exe_win32_server,exe_win64_server],
	U = [u_release,u_shipping],
	UPK = [upk_cooked],
	BUILD = [daily_tool_build,shipping_build],
	
	Vertices = PCS ++ EXE ++ U ++ UPK ++ BUILD,

	Edges = [
		%% minimal tool(umake) build
		{U,exe_win32_release},
		%% pcs, cook requires tool
		{[upk_cooked|PCS],u_release},
		%% daily_tool needs release script and binaries
		{daily_tool_build,[u_release,exe_win32_release,exe_win64_release]},
		%% shipping build needs all except for win64 server and editor binaries
		{shipping_build,[upk_cooked,exe_win32_shipping,exe_win64_shipping,exe_win32_server|PCS]} 
	],
	
	{Edges,Vertices}.

path(root) -> "d:\\r.game\\UnrealEngine3\\";
path(dev) -> path(root) ++ "Development\\";
path(unrealBuildTool) -> path(dev) ++ "Intermediate\\UnrealBuildTool\\Release\\UnrealBuildTool.exe";
path(bin) -> path(root) ++ "Binaries\\";
path(_) -> "".
	
%% worker function
build_native_win32_release() ->
	os:cmd(path(unrealBuildTool) ++ " Win32 Release MyGame -output " ++ path(bin) ++ "\\MyGame.exe" ++ " -noxge").

sync(code) -> say("p4 sync codes");
sync(upk) -> say("p4 sync upk");
sync(build) -> say("p4 sync bin, u");
sync(_) -> say("???").

exeName(release) -> "MyGame.exe";
exeName(shipping) -> "Shipping-MyGame.exe";
exeName(server) -> "DedicatedServer-MyGame.exe";
exeName(_) -> "UNKNOWN".

transaction(Begin,Do,End,Cleanup) ->
	try
		Begin(),
		Do(),
		End()
	catch
		_ -> Cleanup()
	end.

p4op(Target,Fun) ->
	transaction(
		fun() -> say("p4 edit " ++ Target) end,
		Fun,
		fun() -> say("p4 submit") end,
		fun() -> say("p4 revert") end
	).

invoke_ubt(Target,Config) ->
	say("ubt " ++ atom_to_list(Target) ++ " " ++ atom_to_list(Config)),
	timer:sleep(100 * (10+length(atom_to_list(Config))+length(atom_to_list(Target)))).
	
ubt(Target,Config) -> 
	sync(code), 
	p4op( 
		["Binaries\\" ++ atom_to_list(Target) ++ "\\" ++ exeName(Config)],
		fun() -> invoke_ubt(Target,Config) end
	).

do(exe_win32_release) -> ubt(win32,release);
do(exe_win64_release) -> ubt(win64,release);
do(exe_win32_shipping) -> ubt(win32,shipping);
do(exe_win64_shipping) -> ubt(win64,shipping);
do(exe_win32_server) -> ubt(win32,server);
do(exe_win64_server) -> ubt(win64,server);

do(_Work) -> 
	io:format("undefined do ~p ~n",[_Work]).


%% Some helper methods.

say(Format) ->
  say(Format, []).
say(Format, Data) ->
  io:format("~p:~p: ~s~n", [?MODULE, self(), io_lib:format(Format, Data)]).